// pages/funcs/share.js
const App = getApp()
const QR = require("qrcode-base64")
import Kits from '../../utils/kits'
import Util from '../../utils/util'

Page({
  data: {
    init: false,

    title: '',
    src: ''
  },
  onLoad(options) {
    if (options.params) {
      let title = '分享'
      let body = {}
      const params = JSON.parse(options.params)

      title = '分享车辆'
      body = {
        cid: params.info.car.id,
        mid: params.info.mch.id,
      }
      this.setData({
        title: title
      })

      App.doPost({
        uri: '/app/base/tool/share/url',
        body: {
          type: params.type,
          data: JSON.stringify(body)
        },
        fnSucc: resp => {
          this.drawQr(params, resp.data.url)
        },
        fnFail: resp => {
          Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
          wx.navigateBack({
            delta: 1,
          })
        }
      })
      return
    }
    this.getOpenerEventChannel().on('accept', (data) => {
      let title = '分享'
      let body = {}
      if (data.type == 'order_share') {
        title = '分享订单'
        body = {
          qrurl: data.info.data.url
        }
      } else if (data.type == 'car_share') {
        title = '分享车辆'
        body = {
          cid: data.info.car.id,
          mid: data.info.mch.id,
        }
        console.log('body', body);
      } else if (data.type == 'mch_share') {
        title = '分享门店'
        body = {
          mid: data.info.mch.id,
        }
      } else if (data.type == 'clerk_invite') {
        title = '邀请绑定'
        body = {
          uid: data.info.clk.id
        }
      }
      this.setData({
        title: title
      })

      if (body.qrurl) {
        this.drawQr(data, body.qrurl)
      } else {
        App.doPost({
          uri: '/app/base/tool/share/url',
          body: {
            type: data.type,
            data: JSON.stringify(body)
          },
          fnSucc: resp => {
            this.drawQr(data, resp.data.url)
          },
          fnFail: resp => {
            Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
            wx.navigateBack({
              delta: 1,
            })
          }
        })
      }

    })
  },
  drawQr(data, url) {
    var imgData = QR.drawImg(url, {
      typeNumber: 4,
      errorCorrectLevel: 'M',
      size: 340
    })
    let path = wx.env.USER_DATA_PATH + '/' + new Date().getTime() + '.png'
    wx.getFileSystemManager().writeFile({
      filePath: path,
      data: imgData.slice(22),
      encoding: 'base64',
      success: () => {
        if (data.type == 'order_share') {
          this.drawOrderShare(data, path)
        } else if (data.type == 'car_share') {
          this.drawCarShare(data, path)
        } else if (data.type == 'mch_share') {
          this.drawMchShare(data, path)
        } else if (data.type == 'clerk_invite') {
          this.drawClerkInvite(data, path)
        }
      }
    })
  },
  drawClerkInvite(data, qrfile) {
    let clk = data.info.clk

    wx.getImageInfo({
      src: `https://cdn.hangzhouyizuke.com/res/share/clerk_invite_bg.png`,
      success: (bg) => {
        let ctx = wx.createCanvasContext('cas')

        ctx.drawImage(bg.path, 0, 0, 750, 1334)

        ctx.font = 'bold 32px sans-serif'
        ctx.fillText(clk.mch, (750 - ctx.measureText(clk.mch).width) / 2, 560, 750)

        ctx.draw(true)

        ctx.font = 'bold 64px sans-serif'
        ctx.setFillStyle('#ff5400')
        ctx.fillText(clk.bind.pwd, (750 - ctx.measureText(clk.bind.pwd).width) / 2, 740, 750)
        ctx.draw(true)

        ctx.drawImage(qrfile, 205, 800, 340, 340)

        ctx.draw(true)
        setTimeout(() => {
          this.showImage()
        }, 800);
      }
    })

  },
  drawCarShare(data, qrfile) {
    let car = data.info.car

    wx.getImageInfo({
      src: `https://cdn.hangzhouyizuke.com/res/share/car_share_bg.png`,
      success: (bg) => {
        let ctx = wx.createCanvasContext('cas')

        ctx.drawImage(bg.path, 0, 0, 750, 1334)

        wx.getImageInfo({
          src: car.cover,
          success: (file) => {

            ctx.drawImage(file.path, 0, 80, 750, 375)

            ctx.font = 'bold 32px sans-serif'
            ctx.fillText(car.name, 100, 600, 550)
            ctx.draw(true)

            ctx.font = 'bold 48px sans-serif'
            ctx.setFillStyle('#ff3333')
            ctx.fillText('￥ ' + car.price.mdpStr + ' 元/天', 100, 700, 550)
            ctx.draw(true)

            ctx.drawImage(qrfile, 205, 800, 340, 340)

            ctx.draw(true)
            setTimeout(() => {
              this.showImage()
            }, 800);
          }
        })
      }
    })

  },

  drawMchShare(data, qrfile) {
    let mch = data.info.mch

    wx.getImageInfo({
      src: `https://cdn.hangzhouyizuke.com/res/share/mch_share_bg.png`,
      success: (bg) => {
        let ctx = wx.createCanvasContext('cas')

        ctx.drawImage(bg.path, 0, 0, 750, 1334)

        ctx.font = 'bold 32px sans-serif'
        ctx.fillText(mch.name, (750 - ctx.measureText(mch.name).width) / 2, 560, 750)
        ctx.draw(true)

        ctx.font = 'bold 24px sans-serif'
        ctx.setFillStyle('#ff5400')
        ctx.fillText("S" + mch.id, (750 - ctx.measureText("S" + mch.id).width) / 2, 700, 750)
        ctx.draw(true)

        let memo = '扫码查看可用车辆'

        ctx.font = '24px sans-serif'
        ctx.setFillStyle('#888')
        ctx.fillText(memo, (750 - ctx.measureText(memo).width) / 2, 750, 750)
        ctx.draw(true)

        ctx.drawImage(qrfile, 205, 800, 340, 340)

        ctx.draw(true)
        setTimeout(() => {
          this.showImage()
        }, 800);
      }
    })

  },
  drawOrderShare(data, qrfile) {
    let car = data.info.car
    let param = data.info.param
    wx.getImageInfo({
      src: `https://cdn.hangzhouyizuke.com/res/share/order_share_bg.png`,
      success: (bg) => {
        let ctx = wx.createCanvasContext('cas')

        ctx.drawImage(bg.path, 0, 0, 750, 1334)

        wx.getImageInfo({
          src: car.cover,
          success: (file) => {

            ctx.drawImage(file.path, 0, 80, 750, 375)

            ctx.font = 'bold 32px sans-serif'
            ctx.fillText(car.name, 100, 600, 550)
            ctx.draw(true)

            ctx.font = '26px sans-serif'
            ctx.setFillStyle('#666666')
            ctx.fillText('起止日期：' + `${param.begin.split(' ')[0]} 至 ${param.close.split(' ')[0]}`, 100, 660, 550)
            ctx.draw(true)

            ctx.fillText('每日租金：' + Kits.fmtMoneyString(param.custom.day) + ' 元/天', 100, 710, 550)
            ctx.draw(true)

            ctx.setFillStyle('#ff3333')

            ctx.fillText('合计租金：￥' + param.totalStr, 100, 760, 550)
            ctx.draw(true)

            ctx.drawImage(qrfile, 205, 800, 340, 340)

            ctx.draw(true)
            setTimeout(() => {
              this.showImage()
            }, 800);
          }
        })
      }
    })

  },
  // 显示图片
  showImage() {
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 750,
      height: 1334,
      destWidth: 750,
      destHeight: 1334,
      canvasId: 'cas',
      success: (res) => {
        this.setData({
          init: true,
          src: res.tempFilePath
        })
      }
    })
  },

  // // 保存图片到本地
  // doSaveImage() {
  //   wx.getSetting({
  //     success: (res) => {
  //       if (!res.authSetting['scope.writePhotosAlbum']) {
  //         wx.authorize({
  //           scope: 'scope.writePhotosAlbum',
  //           success: () => {
  //             wx.saveImageToPhotosAlbum({
  //               filePath: this.data.src,
  //               success: () => {
  //                 Util.Toast.succ('保存成功')
  //               }
  //             })
  //           }
  //         })
  //       } else {
  //         wx.saveImageToPhotosAlbum({
  //           filePath: this.data.src,
  //           success: () => {
  //             Util.Toast.succ('保存成功')
  //           }
  //         })
  //       }
  //     }
  //   })

  // },
  // 将图片发送给微信
  doSendImage() {
    wx.showShareImageMenu({
      path: this.data.src
    })
  },
})